package com.joinway.framework.support.security.validator;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.joinway.framework.bean.exception.SessionExpiredException;
import com.joinway.framework.bean.security.annotation.Security;
import com.joinway.framework.bean.security.type.CheckAction;
import com.joinway.framework.bean.security.type.CheckPoint;
import com.joinway.framework.core.utils.AopHelper;

public class SessionValidator implements ISecurityValidator {

	private static final String SESSION_ALIVE_KEY = "com.joinway.security.session.alive.key";
	
	@Override
	public void validate(ProceedingJoinPoint point) throws SessionExpiredException {
		
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		
//		Login login = AopHelper.getAnnotation(point, Login.class, false);
		
		Security security = AopHelper.getAnnotation(point, Security.class, true);
		
		if(security.action() == CheckAction.Login){
			request.getSession().setAttribute(SESSION_ALIVE_KEY, UUID.randomUUID().toString());
		}else{
			Object value = request.getSession().getAttribute(SESSION_ALIVE_KEY);
			if(value == null){
				throw new SessionExpiredException();
			}
		}
	}

	@Override
	public CheckPoint getCheckPoint() {
		return CheckPoint.Session;
	}

}
